package com.uenpay.im.invokeitems.login;

import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.utilities.DateUtils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.QYXUserEntity;
import com.uenpay.im.serializations.QYXUserSerializer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 登录
 * @author SL
 * @copyRight http://www.qiyunxin.com
 *
 */
public class LoginInvokItem extends HttpInvokeItem {

	public class LoginInvokItemResult {
		public int status;
		public String msg;
		public QYXUserEntity user;
	}

	public LoginInvokItemResult getOutput() {
		return (LoginInvokItemResult) GetResultObject();
	}

	public LoginInvokItem(String mobilePhone, String pwd) {
		String time = DateUtils.getCurrentSeconds() + "";
		String sign = Utils.md5(Utils.md5(mobilePhone + "_" + time));
		String url = APIConfiguration.getBaseUrl() + "Cust/Init/login?";
		HashMap<String, String> mRequestParams = new HashMap<String, String>();
		mRequestParams.put("username", mobilePhone);
		mRequestParams.put("password", pwd);
		mRequestParams.put("time", time);
		mRequestParams.put("sign", sign);
		mRequestParams.put("logintype", "1");
		SetRequestParams(mRequestParams);
		SetMethod("POST");
		SetUrl(url);
	}

	@Override
	protected Object DeserializeResult(String responseBody) {
		LoginInvokItemResult result = new LoginInvokItemResult();
		try {
			JSONObject json = new JSONObject(responseBody);
			result.status = json.optInt("status");
			result.msg = json.optString("msg");
			JSONObject dataJson = json.optJSONObject("data");
			if (dataJson != null) {
				IMApplication.getInstance().setLoginInfo(
						dataJson.optString("custid"),
						dataJson.optString("token"),dataJson.optString("auth"));
				IMApplication.getInstance().setUcrToken(dataJson.optString("ucrtoken"));
				IMApplication.getInstance().setUcrOpenId(dataJson.optString("ucropenid"));
				result.user = QYXUserSerializer.deserializeUser(dataJson);
			}

		} catch (JSONException e) {
			e.printStackTrace();
			return result;
		}

		return result;
	}

}
